import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@fastgpt/service/common/response';
import { connectToDatabase } from '@/service/mongo';
import { MongoUser } from '@fastgpt/service/support/user/schema';
import { PostLoginProps } from '@fastgpt/global/support/user/api';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    await connectToDatabase();
    const { username, password, pid } = req.body as PostLoginProps;
    const user = await MongoUser.findOne({ username });
    if (user) {
      // throw new Error('用户已存在');
      jsonRes(res, {
        data: user
      });
      return;
    }
    const data = await MongoUser.create({
      username: username,
      password: password,
      pid: pid
    });

    jsonRes(res, {
      data
    });
  } catch (err) {
    jsonRes(res, {
      code: 500,
      error: err
    });
  }
}
